import store from '../../westore/store'
import create from '../../westore/utils/create'

import Config from "../../config"
import Api from "../../utils/api"
import {
  Modal
} from "../../utils/common"
import deepCopy from "../../utils/common"
const app = getApp(),
  regeneratorRuntime = require("../../utils/regenerator-runtime/runtime")
const player = wx.getBackgroundAudioManager()
create(store, {
  data: {
    openid: "",
    userInfo: null,
    id:"",
    allplaying:false,
    playover:false,
    progress:"0%",
    player: "",
    duration:"00:00",
    currentTime:"00:00",
    customEnd:false,
    tips:[
      "在体验过程中有任何疑问，欢迎来「社区」互动！",
      "为您的坚持点赞。每天3分钟，轻松减压，积蓄力量，继续向前行。欢迎参与「社区」互动。",
      "欢迎您参与「社区」互动，分享感受，让更多人得到启发。",
      "连续坚持7天了，为您点赞。欢迎参与「社区」互动，分享您的感受或困惑。",
      "恭喜您连续坚持14天，这是一个可喜的成就。欢迎参与「社区」互动，分享您的心得。" ,
      "恭喜您连续坚持21天！欢迎继续坚持，欢迎您到「社区」分享感受，帮助更多人轻松减压，用更好的状态，向前行。"],
    tip:"",
    playlist: [],
    day:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    const _this = this;
    const id = options.id;
    console.log("load");
    const autoplay = options.date||false;
    let openid = wx.getStorageSync("openid");
    if (openid === "") {
      const data = await Api.Login()
      openid = data.openid;
      _this.store.data.openid = data.openid;
    }
    const res = await Api.getSettingById(openid,id);
    console.log(res);
    let day = 0;
    if(res.status=="0"){
      let list = res.data.detail;
      const now = new Date();
      list.map(e=>{
        let actdate = new Date(e.act_date);
        e.cantplay = now - actdate < 0;
        if (e.complete==1) day++;
        e.isplaying = false;
        e.timer=""
        return e;
      })
      let tip = ""
      switch (day) {
        case 1: tip = _this.data.tips[0]; break;
        case 7: tip = _this.data.tips[3]; break;
        case 14: tip = _this.data.tips[4]; break;
        case 21: tip = _this.data.tips[5]; break;
        default: tip = _this.data.tips[Math.floor(Math.random() * 3)]; break;
      }
      console.log(day);
      _this.setData({
        tip,
        day
      })
      player.title= "暂停3分钟"
      player.onPlay(function () {
        const playing = `playlist[${player._playindex}].isplaying`
        _this.setData({
          [playing]: true,
          allplaying:true,
          playover:false,
          customEnd:false
        })
        wx.hideLoading();
      })
      player.onEnded(async function () {
        console.log(player._playindex)
        console.log(player._date)
        const playing = `playlist[${player._playindex}].isplaying`
        const complete = `playlist[${player._playindex}].complete`
        _this.updateTip();
        const res = await Api.settingcomplete(openid, id, player._date)
        _this.setData({
          [complete]: true,
          progress:"0%",
          [playing]: false,
          playover: true,
        })
      })
      player.onStop(function (){
        const playing = `playlist[${player._playindex || 0}].isplaying`
        _this.setData({
          [playing]: false,
          progress: "0%",
          playover: true,
        })
        if(!_this.data.customEnd){
          _this.setData({
            allplaying: false,
          })
        }
      })
      player.onTimeUpdate(function () {
        let times = 1;
        let duration = _this.formatTime(player.duration);
        const currentTime = _this.formatTime(player.currentTime);
        if (_this.data.custom == "1" && _this.data.music_length == "3") {
          times = 3.67;
          duration = "3:00";
          if (player.currentTime >= 180) {
            _this.setData({ customEnd:true});
            player.stop();
          }
        }
        if (_this.data.custom == "1" && _this.data.music_length=="5"){
          times = 2.2;
          duration = "5:00";
          if(player.currentTime >= 300){
            _this.setData({ customEnd: true });
            player.stop();
          }
        }
        console.log(_this.data.playlist);
        
        if (_this.data.playlist[player._playindex].complete == 0 && player.currentTime>=180){
          const complete = `playlist[${player._playindex}].complete`
          Api.settingcomplete(openid, id, player._date).then(function(res){
            if (res.status == "0") {
              _this.updateTip();
              _this.setData({
                [complete]: true,
              })
            }
          })
        }
        let progress = '0%';
        if (duration && currentTime){
           progress = ((Number(player.currentTime / player.duration) * 0.9 * times) * 100);
           progress = Number.isNaN(progress)?"0%":progress+'%';
        }
        const timer = `playlist[${player._playindex}].timer`
        _this.setData({
          [timer]: currentTime + '/' + duration,
          progress})
      })
      _this.setData({
        player, playlist: list, id, custom: res.data.custom, music_length: res.data.music_length
      });
      if(autoplay){
        let e = {currentTarget:{dataset:{index:-1}}};
        e.currentTarget.dataset.index = _this.data.playlist.findIndex(e => autoplay == e.act_date)
        if (e.currentTarget.dataset.index > -1) _this.play(e);
      }
    }else{
      wx.showToast({
        title: '获取数据失败，请重新进入小程序',
        icon: 'none'
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    const _this = this;
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const _this = this;
    console.log("show");
    if (_this.data.playlist.length > 0){
      let list = _this.data.playlist;
      const now = new Date();
      console.log(now);
      list.map(e => {
        let actdate = new Date(e.act_date);
        e.cantplay = now - actdate < 0;
        console.log(e.cantplay);
        e.isplaying = false;
        e.timer = ""
        return e;
      })
      _this.setData({
        playlist: list,
      });
    }
  },

  formatTime: function (s){
    let h;
    h = Math.floor(s / 60);
    s = Math.floor(s) % 60;
    h    += '';
    s    += '';
    h  =   (h.length == 1) ? '0' + h : h;
    s  =   (s.length == 1) ? '0' + s : s;
    return h + ':' + s;
  },
  updateTip: function(){
    console.log("updateTip");
    const _this = this;
    let day = _this.data.day;
    let tip = ""
    if (_this.data.playlist[player._playindex].complete == 0) {
      day++;
      switch (day) {
        case 1: tip = _this.data.tips[0]; break;
        case 7: tip = _this.data.tips[3]; break;
        case 14: tip = _this.data.tips[4]; break;
        case 21: tip = _this.data.tips[5]; break;
        default: tip = _this.data.tips[Math.floor(Math.random() * 3)]; break;
      }
      console.log(day);
      _this.setData({
        tip,
        day
      })
    }
  },
  play: async function(e){
    const _this = this;
    const openid = wx.getStorageSync("openid");
    const id = _this.data.id;
    const index = e.currentTarget.dataset.index;
    const date = _this.data.playlist[index].act_date;
    wx.showLoading({
      title: '加载中...',
    })
    const music = await Api.getMusic(openid, id, date);
    if(music.status==0){
      console.log(music.data)
      const lastPlaying = `playlist[${player._playindex||0}].isplaying`
      _this.setData({[lastPlaying]: false})
      player.title = date;
      const src = Config.baseUrl + music.data.url;
      player.src = src;
      console.log(src);
      console.log(player.src);
      player._playindex = index;
      player._date = date;
    }else{
      wx.hideLoading();
      wx.showToast({
        title: '加载音乐错误，请重试',
        icon: 'none'
      })
    }

  },
  pause: function(){
    const _this = this;
    const playing = `playlist[${player._playindex}].isplaying`
    _this.setData({
      [playing]: false,
      allplaying: false
    })
    player.pause();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    console.log("hide");
    // const _this = this;
    // const index = player._playindex;
    // const playing = `playlist[${index}].isplaying`
    // _this.setData({
    //   [playing]: false
    // })
    // player.stop();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("unload");
    const _this = this;
    const index = player._playindex||0;
    const playing = `playlist[${index}].isplaying`
    _this.setData({
      [playing]: false,
      allplaying: false
    })
    player.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})